<template>
  <div class="schedule-management">
    <div class="page-header">
      <h2>排班表管理</h2>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="姓名:">
          <el-input
            v-model="searchForm.employeeName"
            placeholder="请输入人员姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="班组名称:">
          <el-input
            v-model="searchForm.teamName"
            placeholder="请输入班组名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="月份:">
          <el-date-picker
            v-model="searchForm.scheduleMonth"
            type="month"
            placeholder="2025年07月"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">确认检索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button @click="handleCollapse">{{ isExpanded ? '收起' : '收起' }}</el-button>
        <el-button @click="handleCalculate">重算</el-button>
        <el-button type="primary" @click="handleImport" v-if="userStore.isAdmin">确认保存</el-button>
        <el-button type="success" @click="handleExport" v-if="userStore.isAdmin">导出</el-button>
      </div>
    </div>
    
    <!-- 操作按钮区 -->
    <div class="operation-section">
      <el-button @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleDownloadTemplate" v-if="userStore.isAdmin">下载模板</el-button>
      <el-button type="primary" @click="handleImportSchedule" v-if="userStore.isAdmin">导入</el-button>
      <el-button type="success" @click="handleExportSchedule" v-if="userStore.isAdmin">导出</el-button>
    </div>
    
    <!-- 排班表 -->
    <div class="schedule-table">
      <div class="table-title">{{ currentMonth }}月排班表</div>
      
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        class="schedule-table-content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="序号" label="序号" width="60" align="center" fixed="left" />
        <el-table-column prop="teamName" label="班组名称" width="120" fixed="left" />
        <el-table-column prop="employeeName" label="姓名" width="80" fixed="left" />
        <el-table-column prop="employeeNo" label="工号" width="80" fixed="left" />
        
        <!-- 动态生成日期列 -->
        <el-table-column
          v-for="day in dayColumns"
          :key="day.date"
          :label="day.label"
          :prop="day.prop"
          width="65"
          align="center"
          class-name="day-column"
        >
          <template #header>
            <div class="day-header">
              <div>{{ day.day }}</div>
              <div class="weekday">{{ day.weekday }}</div>
            </div>
          </template>
          <template #default="{ row }">
            <div class="shift-cell" :class="getShiftClass(row[day.prop]?.shiftCode)">
              <div class="shift-code">{{ row[day.prop]?.shiftCode || '-' }}</div>
              <div class="shift-hours" v-if="row[day.prop]?.workHours">{{ row[day.prop]?.workHours }}h</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalWorkHours" label="排班总时长" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <div class="total-hours">{{ row.totalWorkHours || 0 }}h</div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total-text">共{{ total }}条记录</span>
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="导入排班表"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="importForm" label-width="100px">
        <el-form-item label="导入月份:" required>
          <el-date-picker
            v-model="importForm.importMonth"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-remove="handleFileRemove"
        :limit="1"
        accept=".xlsx,.xls"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlsx/xls文件
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleImportConfirm" :loading="importDialog.loading">
            确定导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getSchedulePage, importSchedule, exportSchedule, deleteScheduleByEmployees } from '@/api/schedule'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const isExpanded = ref(true)

const searchForm = reactive({
  employeeName: '',
  teamName: '',
  scheduleMonth: dayjs().format('YYYY-MM')
})

const pagination = reactive({
  current: 1,
  size: 10
})

const importDialog = reactive({
  visible: false,
  loading: false
})

const importForm = reactive({
  importMonth: dayjs().format('YYYY-MM')
})

const uploadRef = ref()
const uploadFile = ref(null)

// 表格选中的行
const multipleSelection = ref([])

// 计算属性
const currentMonth = computed(() => {
  return searchForm.scheduleMonth ? dayjs(searchForm.scheduleMonth).format('YYYY年MM') : ''
})

const dayColumns = computed(() => {
  if (!searchForm.scheduleMonth) return []
  
  const date = dayjs(searchForm.scheduleMonth)
  const daysInMonth = date.daysInMonth()
  const columns = []
  
  for (let i = 1; i <= daysInMonth; i++) {
    const currentDate = date.date(i)
    columns.push({
      date: i,
      day: i,
      weekday: ['日', '一', '二', '三', '四', '五', '六'][currentDate.day()],
      label: `${i}`,
      prop: `day${i}`
    })
  }
  
  return columns
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      scheduleMonth: searchForm.scheduleMonth
    }
    
    const res = await getSchedulePage(params)
    const data = res.data
    
    // 处理数据，将dailySchedules转换为day1, day2...格式
    tableData.value = data.records?.map((item, index) => {
      const row = {
        序号: (pagination.current - 1) * pagination.size + index + 1,
        employeeName: item.employeeName,
        employeeNo: item.employeeNumber, // 映射字段名
        teamName: item.teamName,
        teamCode: item.teamCode,
        scheduleMonth: item.scheduleMonth,
        totalWorkDays: item.totalWorkDays,
        totalWorkHours: item.totalWorkHours
      }
      
      // 将dailySchedules转换为day1, day2等属性，包含班次代码和工时
      if (item.dailySchedules) {
        item.dailySchedules.forEach(schedule => {
          const date = dayjs(schedule.scheduleDate)
          const day = date.date()
          row[`day${day}`] = {
            shiftCode: schedule.shiftCode,
            workHours: schedule.scheduledDurationHours || 0
          }
        })
      }
      
      return row
    }) || []
    
    total.value = data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.employeeName = ''
  searchForm.teamName = ''
  searchForm.scheduleMonth = dayjs().format('YYYY-MM')
  pagination.current = 1
  loadData()
}

const handleCollapse = () => {
  isExpanded.value = !isExpanded.value
}

const handleCalculate = () => {
  ElMessage.info('重算功能待实现')
}

const handleImport = () => {
  ElMessage.info('确认保存功能待实现')
}

const handleExport = async () => {
  if (!searchForm.scheduleMonth) {
    ElMessage.warning('请选择要导出的月份')
    return
  }
  
  try {
    const params = {
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      scheduleMonth: searchForm.scheduleMonth
    }
    
    console.log('导出参数:', params)
    ElMessage.info('正在导出，请稍候...')
    
    const res = await exportSchedule(params)
    console.log('导出响应:', res)
    
    // 检查响应是否为blob
    if (!(res instanceof Blob)) {
      throw new Error('导出数据格式错误')
    }
    
    // 检查blob大小
    if (res.size === 0) {
      throw new Error('导出数据为空')
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.href = url
    link.download = `${currentMonth.value}排班表.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    const errorMsg = error.response?.data?.message || error.message || '导出失败'
    ElMessage.error(errorMsg)
  }
}

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的排班记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${multipleSelection.value.length} 条排班记录吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 提取选中行的员工工号
    const employeeNumbers = multipleSelection.value.map(row => row.employeeNo)
    
    console.log('删除参数:', {
      employeeNumbers,
      month: searchForm.scheduleMonth
    })
    
    // 调用删除接口
    const response = await deleteScheduleByEmployees(employeeNumbers, searchForm.scheduleMonth)
    console.log('删除响应:', response)
    
    ElMessage.success('批量删除成功')
    // 清空选择
    multipleSelection.value = []
    // 刷新数据
    await loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      const errorMsg = error.response?.data?.message || error.message || '批量删除失败'
      ElMessage.error(errorMsg)
    }
  }
}

const handleImportSchedule = () => {
  importDialog.visible = true
  uploadFile.value = null
}

const handleExportSchedule = () => {
  handleExport()
}

const handleEdit = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.employeeName}(${row.employeeNo}) 在 ${currentMonth.value} 的排班记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('单个删除参数:', {
      employeeNumbers: [row.employeeNo],
      month: searchForm.scheduleMonth
    })
    
    // 调用删除接口，传入单个员工工号
    const response = await deleteScheduleByEmployees([row.employeeNo], searchForm.scheduleMonth)
    console.log('删除响应:', response)
    
    ElMessage.success('删除成功')
    await loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      const errorMsg = error.response?.data?.message || error.message || '删除失败'
      ElMessage.error(errorMsg)
    }
  }
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  loadData()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

const handleFileChange = (file) => {
  // Element Plus 的 upload 组件会传入一个包装对象，raw 属性才是原始文件
  uploadFile.value = file.raw || file
  console.log('选择的文件:', uploadFile.value)
}

const handleFileRemove = () => {
  uploadFile.value = null
}

const handleImportConfirm = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  if (!importForm.importMonth) {
    ElMessage.warning('请选择导入月份')
    return
  }
  
  importDialog.loading = true
  try {
    await importSchedule(uploadFile.value, importForm.importMonth)
    ElMessage.success('导入成功')
    importDialog.visible = false
    uploadRef.value?.clearFiles()
    uploadFile.value = null
    // 刷新数据，使用当前选择的月份
    searchForm.scheduleMonth = importForm.importMonth
    loadData()
  } catch (error) {
    console.error('导入失败:', error)
    const errorMsg = error.response?.data?.message || error.message || '导入失败'
    ElMessage.error(errorMsg)
  } finally {
    importDialog.loading = false
  }
}

const getShiftClass = (shiftCode) => {
  if (!shiftCode || shiftCode === '-') return 'empty'
  if (shiftCode === 'R') return 'rest'
  if (shiftCode === 'D') return 'day'
  if (shiftCode === 'N') return 'night'
  return 'other'
}

const handleDownloadTemplate = () => {
  // 创建示例数据
  const currentMonth = dayjs().format('YYYY年MM月')
  const daysInMonth = dayjs().daysInMonth()
  
  // 创建表头
  const headers = ['序号', '班组名称', '姓名', '工号']
  
  // 添加日期列
  for (let i = 1; i <= daysInMonth; i++) {
    headers.push(`${i}`)
  }
  
  // 创建示例数据
  const templateData = [
    {
      '序号': 1,
      '班组名称': '生产一组',
      '姓名': '张三',
      '工号': 'EMP001',
      ...Object.fromEntries(Array.from({length: daysInMonth}, (_, i) => [`${i+1}`, i % 3 === 0 ? 'R' : 'D']))
    },
    {
      '序号': 2,
      '班组名称': '生产二组',
      '姓名': '李四',
      '工号': 'EMP002',
      ...Object.fromEntries(Array.from({length: daysInMonth}, (_, i) => [`${i+1}`, i % 3 === 1 ? 'N' : 'D']))
    }
  ]
  
  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(templateData, { header: headers })
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '排班表')
  
  // 设置列宽
  const colWidths = [
    { wch: 8 },   // 序号
    { wch: 15 },  // 班组名称
    { wch: 10 },  // 姓名
    { wch: 12 },  // 工号
    ...Array(daysInMonth).fill({ wch: 5 })  // 日期列
  ]
  ws['!cols'] = colWidths
  
  // 生成Excel文件
  XLSX.writeFile(wb, `${currentMonth}排班表导入模板.xlsx`)
  
  ElMessage.success('模板下载成功！班次代码说明：D-白班(8h), N-夜班(8h), R-休息(0h)')
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.schedule-management {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #333;
      margin: 0;
    }
  }
  
  .search-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .action-buttons {
      display: flex;
      gap: 10px;
    }
  }
  
  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    
    .el-button {
      min-width: 88px;
    }
  }
  
  .schedule-table {
    .table-title {
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #333;
    }
    
    .schedule-table-content {
      :deep(.day-column) {
        .cell {
          padding: 0;
        }
      }
      
      .day-header {
        font-size: 12px;
        line-height: 1.2;
        
        .weekday {
          color: #666;
          font-size: 10px;
        }
      }
      
      .shift-cell {
        width: 100%;
        min-height: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 2px;
        
        .shift-code {
          font-weight: bold;
          font-size: 14px;
        }
        
        .shift-hours {
          font-size: 12px;
          margin-top: 2px;
        }
        
        &.rest {
          background: #f0f0f0;
          color: #666;
        }
        
        &.day {
          background: #e6f7ff;
          color: #1890ff;
        }
        
        &.night {
          background: #fff7e6;
          color: #fa8c16;
        }
        
        &.other {
          background: #f6ffed;
          color: #52c41a;
        }
        
        &.empty {
          color: #d9d9d9;
        }
      }
      
      .total-hours {
        font-weight: bold;
        color: #1890ff;
        font-size: 16px;
      }
    }
    
    .pagination-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      
      .total-text {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

:deep(.el-upload-dragger) {
  height: 120px;
}
</style>